import os
import json
import numpy as np
from typing import List, Dict, Optional
from sklearn.metrics.pairwise import  euclidean_distances

from app.services import FACES_DIR, CONFIG_FILE


os.makedirs(FACES_DIR, exist_ok=True)
os.makedirs(os.path.dirname(CONFIG_FILE), exist_ok=True)


if not os.path.exists(CONFIG_FILE):
    with open(CONFIG_FILE, "w") as f:
        json.dump({
            "backup_password": "admin123",
            "openai_api_key": "你的OpenAI密钥"
        }, f)


def get_backup_password() -> str:
    """
    获取备用密码
    :return:
    """
    try:
        with open(CONFIG_FILE, "r") as f:
            config = json.load(f)
            return config.get("backup_password", "admin123")
    except Exception as e:
        print(f"读取配置文件错误: {e}")
        return "admin123"


def verify_backup_password(password: str) -> bool:
    """
    验证备用密码
    :param password:
    :return:
    """
    backup_password = get_backup_password()
    return password == backup_password


def save_face_descriptor(user_name,descriptor: List[float]) -> str:
    """
    保存人脸特征描述符，返回用户ID
    :param user_name:
    :param descriptor:
    :return:
    """
    user_id = str(user_name)

    file_path = os.path.join(FACES_DIR, f"{user_name}.json")
    with open(file_path, "w") as f:
        json.dump({"descriptor": descriptor}, f)

    return user_id


def verify_face_descriptor(descriptor: List[float], threshold: float = 0.4) -> Optional[str]:
    """
    验证人脸特征描述符，如果匹配返回用户ID
    :param descriptor:
    :param threshold:
    :return:
    """

    input_descriptor = np.array(descriptor).reshape(1, -1)
    print(FACES_DIR)

    for filename in os.listdir(FACES_DIR):
        if filename.endswith(".json"):
            file_path = os.path.join(FACES_DIR, filename)

            with open(file_path, "r") as f:
                try:
                    data = json.load(f)
                    saved_descriptor = np.array(data["descriptor"]).reshape(1, -1)

                    distance = euclidean_distances(input_descriptor, saved_descriptor)[0][0]
                    print(distance)
                    print(threshold)
                    if distance < threshold:
                        return filename.split(".")[0]  # 返回用户ID
                except Exception as e:
                    print(f"处理人脸文件错误: {e}")

    return None


def get_all_faces() -> List[Dict]:
    """
    获取所有已注册的人脸信息
    :return:
    """
    faces = []
    for filename in os.listdir(FACES_DIR):
        if filename.endswith(".json"):
            user_id = filename.split(".")[0]
            faces.append({"user_id": user_id})
    return faces